const browserSync = require("browser-sync");
const { src, dest, parallel, series, watch } = require("gulp");
const babel = require("gulp-babel");
const htmlmin = require("gulp-htmlmin");
const inject = require("gulp-inject");
const less = require("gulp-less");
const terser = require("gulp-terser");

// 1. 对html打包
const htmlTask = () => {
  return src("./src/**/*.html")
    .pipe(htmlmin({ collapseWhitespace: true }))
    .pipe(dest("./dist"));
};

// 2. 对JavaScript打包
const jsTask = () => {
  return src("./src/**/*.js")
    .pipe(babel())
    .pipe(terser({ toplevel: true }))
    .pipe(dest("./dist"));
};

// 3. 对less打包
const lessTask = () => {
  return src("./src/**/*.less").pipe(less()).pipe(dest("./dist"));
};

// 4. 在html中注入js，css
const injectTash = () => {
  return src("./dist/**/*.html")
    .pipe(
      inject(src(["./dist/**/*.js", "./dist/**/*.css"]), { relative: true })
    )
    .pipe(dest("./dist"));
};

// 开启本地服务
const bs = browserSync.create();
const serve = () => {
  watch("./src/**", buildTask);
  bs.init({
    port: 8080,
    open: true,
    files: "./dist/*", // 刷新浏览器
    server: {
      baseDir: "./dist",
    },
  });
};

const buildTask = series(parallel(htmlTask, jsTask, lessTask), injectTash);
const serverTask = series(buildTask, serve);

module.exports = {
  buildTask,
  serverTask,
};
